package com.service.school.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.base.BaseDaoI;
import com.model.TGrade;
import com.pageModel.DataGrid;
import com.pageModel.Grade;
import com.service.school.GradeServiceI;

@Service(value = "gradeService")
public class GradeServiceImpl implements GradeServiceI {

	private BaseDaoI<TGrade> gradeDao;

	public BaseDaoI<TGrade> getGradeDao() {
		return gradeDao;
	}
	@Autowired
	public void setGradeDao(BaseDaoI<TGrade> gradeDao) {
		this.gradeDao = gradeDao;
	}
	@Override
	public List<TGrade> getGradeCmb(Grade grade) {
		String hql="from TGrade t where t.isEnable ='是'";
		List<TGrade> l = gradeDao.find(hql);
		return l;
	}
	@Override
	public DataGrid datagrid(Grade grade) {
		DataGrid dg = new DataGrid();
		String hql="from TGrade t where 1=1 ";
		if(grade.getGradeId()!=null&&!grade.getGradeId().trim().equals("")){
			hql+="and t.gradeId='"+grade.getGradeId()+"'";
		}
		if(grade.getIsEnable()!=null&&!grade.getIsEnable().trim().equals("")){
			hql+=" and t.isEnable='"+grade.getIsEnable()+"'";
		}
		if(grade.getGradeName()!=null&&!grade.getGradeName().trim().equals("")){
			hql+=" and t.gradeName='"+grade.getGradeName()+"'";
		}
		String totalHql = "select count(*) " + hql;
		List<TGrade> l = gradeDao.find(hql, grade.getPage(), grade.getRows());
		List<Grade> nl = new ArrayList<Grade>();
		if (l != null && l.size() > 0) {
			for (TGrade t : l) {
				Grade u = new Grade();
				BeanUtils.copyProperties(t, u);
				nl.add(u);
			}
		}
		dg.setTotal(gradeDao.count(totalHql));
		dg.setRows(nl);
		return dg;
	}
	@Override
	public void remove(String ids) {
		String[] nids = ids.split(",");
		String hql = "delete TGrade t where t.id in(";
		for (int i = 0; i < nids.length; i++) {
			if (i > 0) {
				hql += ",";
			}
			hql += "'" + nids[i] + "'";
		}
		hql += ")";
		gradeDao.executeHql(hql);
	}
	@Override
	public boolean add(Grade grade) {
		Long count = gradeDao.count("select count(*) from TGrade obj where obj.gradeId=?", new Object[] {grade.getGradeId()});
		if (count != null && count > 0) {
			 return  false;
		}
		TGrade t=new TGrade();
		t.setId(UUID.randomUUID().toString());
		t.setGradeId(grade.getGradeId());
		t.setGradeName(grade.getGradeName());
		t.setIsEnable("是");
		gradeDao.saveOrUpdate(t);
		return true;
	}
	@Override
	public void edit(Grade grade) {
		TGrade t=gradeDao.get(TGrade.class,grade.getId());
		BeanUtils.copyProperties(grade, t);
	}
	
}
